<template>
  <GcTable
    v-loading="loading"
    :columns="FRIEND_LINK_COLUMNS"
    :tableData="tableData"
    :showPage="false"
    :showFilter="false"
    :showSearch="false">
    <template #btn-group>
      <el-button type="primary"
        @click="currentFriendLink = null; linkVisible = true"
        v-permission="'friend-link-permission:btn:add'">新增友链</el-button>
    </template>
    <template #logo="{ row }">
      <el-image
        v-if="row.logo"
        :z-index="999999"
        preview-teleported
        style="width: 28px; height: 28px"
        :src="row.logo"
        :zoom-rate="1.2"
        :preview-src-list="[row.logo]"
        fit="cover"
      />
    </template>
    <template #operate="{ row }">
      <div class="operate-btn-group center">
        <gc-icon-button
          type="link"
          @click="updateFriendLink(row)"
          v-permission="'friend-link-permission:btn:edit'">编辑</gc-icon-button>
        <gc-icon-button
          type="link"
          @click="deleteFriendLink([row.id])"
          v-permission="'friend-link-permission:btn:delete'">删除</gc-icon-button>
      </div>
    </template>
  </GcTable>
  <OperateFriendLink
    v-if="linkVisible"
    @close-modal="closeModal"
    :friendLinkInfo="currentFriendLink" />
</template>

<script setup lang="ts" name="FriendShip">
import { ref } from 'vue'
import { FRIEND_LINK_COLUMNS } from './const'
import usePagination from '@/hooks/usePagination'
import { apiGetFriendLinkList, apiDeleteFriendLinks } from '@/http/service'
import { type FriendLink } from '@/http/type'
import OperateFriendLink from './components/OperateFriendLink.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const { loading } = usePagination()
const tableData = ref<FriendLink[]>([])
const linkVisible = ref(false)
const currentFriendLink = ref<null | FriendLink>(null)

async function findFriendLinkList () {
  loading.value = true
  try {
    const data = await apiGetFriendLinkList<FriendLink[]>()
    tableData.value = data
  } catch (error) {
    tableData.value = []
  } finally {
    loading.value = false
  }
}
findFriendLinkList()

function updateFriendLink (linkItem: FriendLink) {
  currentFriendLink.value = linkItem
  linkVisible.value = true
}

async function deleteFriendLink (ids: Array<number>) {
  await ElMessageBox.confirm('删除友情链接后将无法恢复？', '提示', { type: 'warning' })
  await apiDeleteFriendLinks({ ids })
  ElMessage.success('删除友情链接成功')
  findFriendLinkList()
}

function closeModal (update?: boolean) {
  if (update) {
    findFriendLinkList()
  }
  linkVisible.value = false
}
</script>

<style lang="scss" scoped></style>
